package cn.security.auth.filter;

import cn.security.auth.common.Result;
import cn.security.auth.service.LoginService;
import cn.security.auth.util.JwtUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class AuthenticationFilter extends OncePerRequestFilter {
    private static final String AUTHORIZATION_HEADER = "Authorization";
    @Autowired
    private LoginService loginService;
    @Value("${custom.security.default.account}")
    private String defaultAccount;
    @Value("${custom.security.default.password}")
    private String defaultPassWord;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String bearerToken = request.getHeader(AUTHORIZATION_HEADER);

        // 为空放行，后面的filter会处理
        if (!StringUtils.hasText(bearerToken)) {
            filterChain.doFilter(request, httpServletResponse);
            return;
        }

        if (bearerToken.startsWith("Bearer ")) {
            // todo:redis获取用户信息,判断用户是否存在,返回用户信息
            String userId = null;
            try {
                bearerToken = bearerToken.replace("Bearer ", "");
                userId = JwtUtil.getUserIdByToken(bearerToken);
                if (userId != null && defaultAccount.equals(userId)) {
                    User loginUser = loginService.getDefaultLoginUser();
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
                    authenticationToken.setDetails(loginUser);
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            } catch (Exception e) {
                SecurityContextHolder.clearContext();
            }
        }

        filterChain.doFilter(request, httpServletResponse);
    }

}
